package ecom.stateless;

import javax.ejb.Stateless;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerService;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;

import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;


import ecom.api.*;
import ecom.entity.AnnonceChercheurEntity;
import ecom.entity.ConverterEntity;

@Stateless(mappedName = "ecom.stateless.TimerSessionBeanConverterStateless@Remote", description = "TimerSessionBeanConverterStateless", name = "TimerSessionBeanConverterStateless")
public class TimerSessionBeanConverterStateless implements ITimerSessionBeanConverterStateless {

	@Resource
	TimerService timerService;
	
	@PersistenceContext
    private EntityManager m_EntityManager = null; 
	
	private Log logger = LogFactory.getLog(TimerSessionBeanConverterStateless.class);
			

	public TimerSessionBeanConverterStateless() {
		logger.info("TimerSessionBeanConverterStateless created");		
	}

	public void createTimer(long intervalDuration) {
		Timer timer = timerService.createTimer(intervalDuration,
				"Created new timer");
	}

	@Timeout
	public void timeout(Timer timer) {
		logger.info("Timeout occurred!!!!!!!!!!!!!");
		try {
			System.out.println("Connecting to Servlet");

			//URL url = new URL("http://localhost:8090/examples/servlets/servlet/Devise");
			// Open the file 

			Properties props = new Properties();
			URL urlProper = ClassLoader.getSystemResource("conf.properties");
			String urlString = "";
			try {
				props.load(urlProper.openStream());
				urlString =  props.getProperty("urlConverter");
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			URL url = new URL(urlString);
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);
			BufferedReader in =
					new BufferedReader( new InputStreamReader( conn.getInputStream() ) );
			
			String response;
			while ( (response = in.readLine()) != null ) {
				if (response.contains("dollar"))
				{
					try{
						String valueDollarString = response.substring(8);
						Double valueDevice = Double.valueOf(valueDollarString);
						logger.info("dollar value is:" + valueDevice);	
						
						String nameDevice = "dollar";
						
						//update the table ConverterEntity
						logger.info("starting the table ConverterEntity update");
						List<ConverterEntity> listConverter = m_EntityManager.createQuery("select t from ConverterEntity t").getResultList();
						long idDevice=-1;
						for(ConverterEntity converter : listConverter)
				    	{
							if(converter.getNameDevice().equals(nameDevice))
				    			idDevice = converter.getId();   		
				    	}
						if(idDevice>=0)
						{
						
						ConverterEntity modifDevice = m_EntityManager.find(ConverterEntity.class, idDevice);
						modifDevice.setNameDevice(nameDevice);
						modifDevice.setValue(valueDevice);
						m_EntityManager.merge(modifDevice);
						logger.info("updated entry in table ConverterEntity");
						}
						else
						{
							
							ConverterEntity modifDevice = new ConverterEntity(nameDevice, valueDevice);							
							m_EntityManager.persist(modifDevice);
							logger.info("created new entry in table ConverterEntity");
						}
						logger.info("ending the datatable ConverterEntity update");
						
						
					}catch(Exception e)
					{
						
					}
				}
					
			}			
			in.close();
			
			
			//recuparation des messages avec les mails des personnes et les titre des annonces crees
			//ces messages sont dans un queue
			//envoie des mail de confirmation de la publication de l'annonce
			
			
			
			try{
				System.out.println("create consumer");
				//Consumer c = new Consumer();
				//c.getMessage();
				TextListener t = new TextListener();
				
			}catch(Exception e)
			{
				
			}
			
			
		}catch(Exception e)
		{
			logger.error(e.toString());
		}
		
		
		
		logger.info("created another timer with 4 minutes");
		createTimer(240000);
	}

}
